package com.jolink.omiis.wechat.api.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.jolink.omiis.wechat.api.IRobotApi;

/**
 * @author WangYanqing
 *
 * @param <T>
 */
public class RobotApiImpl<T> extends WeChatApiBaseService implements IRobotApi<T> {

	private static Logger logger = LoggerFactory.getLogger(RobotApiImpl.class);

	@SuppressWarnings({ "unchecked" })
	@Override
	public T query(String userId, String msgType, String question, String conversationId, String channelId) {
		long t1 = System.currentTimeMillis();
		logger.info("开始调用智能机器人接口，userId：{}，question：{}，conversationId：{}，channelId：{}。", userId, question,
				conversationId, channelId);
		String baseUri = "http://" + getContext().getServiceUtil().getConfiguration().getValue("OMIIS_ROBOT_HOST")
				+ ":7003/bionRobot/query";
		JsonObject root = new JsonObject();
		root.addProperty("userId", userId);
		root.addProperty("question", question);
		root.addProperty("msgType", msgType);
		root.addProperty("conversationId", conversationId);
		root.addProperty("channelId", channelId);
		logger.info("调用智能机器人接口请求参数：{}。", root.toString());
		String result = (String) executePost(baseUri, "", root.toString());
		long t2 = System.currentTimeMillis();
		logger.info("调用智能机器人接口返回结果，{}，耗时：{}毫秒。", result, (t2 - t1));
		return (T) result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getConversationId(String userId, String greeting, String channelId) {
		long t1 = System.currentTimeMillis();
		logger.info("开始调用智能机器人接口，获取会话ID，userId：{}，greeting：{}，channelId：{}。", userId, greeting, channelId);
		String baseUri = "http://" + getContext().getServiceUtil().getConfiguration().getValue("OMIIS_SERVER_HOST")
				+ ":7003/bionRobot/initConversation";
		Map<String, String> reqParams = new HashMap<String, String>();
		reqParams.put("userId", userId);
		reqParams.put("greeting", greeting);
		reqParams.put("channelId", channelId);
		String result = executeGet(baseUri, reqParams);
		long t2 = System.currentTimeMillis();
		logger.info("调用智能机器人接口返回结果，{}，耗时：{}毫秒。", result, (t2 - t1));
		return (T) result;
	}

	@Override
	public T queryRobotDetail(String userId, String conversationId, String channelId) {
		// 微信接口暂无用到
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jolink.omiis.wechat.api.IRobotApi#query2(java.lang.String,
	 * java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public T query2(String userId, String question, String conversationId, String channelId) {
		return query2(userId, question, conversationId, channelId, null);
	}

	/**
	 * 
	 * 模拟机器人结果
	 * 
	 * @return
	 */
	private static String simulateAnswer() {
		BufferedReader br = null;
		FileReader fr = null;
		StringBuffer answerMsg = new StringBuffer();
		String answerFile = "./robot/1.txt";
		try {
			fr = new FileReader(new File(answerFile));
			br = new BufferedReader(fr);
			String line = null;
			while ((line = br.readLine()) != null) {
				answerMsg.append(line);
			}
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				fr.close();
				br.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return answerMsg.toString();
	}

	@Override
	public T query2(String userId, String question, String conversationId, String channelId, String routingId) {
		long t1 = System.currentTimeMillis();
		logger.info("开始调用智能机器人接口，userId：{}，question：{}，conversationId：{}，channelId：{}，routingId。", userId, question,
				conversationId, channelId, routingId);
		String baseUri = "http://" + getContext().getServiceUtil().getConfiguration().getValue("OMIIS_SERVER_HOST")
				+ ":7003/robot/queryAnswer";
		Map<String, String> reqParams = new HashMap<String, String>();
		reqParams.put("userId", userId);
		reqParams.put("question", question);
		reqParams.put("conversationId", conversationId);
		reqParams.put("channelId", channelId);
		if (!StringUtils.isEmpty(routingId)) {
			reqParams.put("subChannelId", routingId);
		}
		logger.info("调用智能机器人接口请求参数：{}。", reqParams);
		String result = (String) executeGet(baseUri, reqParams);
		long t2 = System.currentTimeMillis();
		logger.info("调用智能机器人返回结果，{}，耗时：{}毫秒。", result, (t2 - t1));
		boolean isActiveSimulate = getContext().getServiceUtil().getConfiguration()
				.getBoolean("OMIIS_IS_ACTIVE_SIMULATE");
		if (isActiveSimulate) {
			return (T) simulateAnswer();
		}
		return (T) result;
	}

	@Override
	public T query2(String userId, String openId, String question, String conversationId, String channelId,
			String routingId) {
		long t1 = System.currentTimeMillis();
		logger.info("开始调用智能机器人接口，userId：{}，question：{}，conversationId：{}，channelId：{}，routingId。", userId, question,
				conversationId, channelId, routingId);
		String baseUri = "http://" + getContext().getServiceUtil().getConfiguration().getValue("OMIIS_SERVER_HOST")
				+ ":7003/robot/queryAnswer";
		Map<String, String> reqParams = new HashMap<String, String>();
		reqParams.put("userId", userId);
		reqParams.put("openId", openId);
		reqParams.put("question", question);
		reqParams.put("conversationId", conversationId);
		reqParams.put("channelId", channelId);
		if (!StringUtils.isEmpty(routingId)) {
			reqParams.put("subChannelId", routingId);
		}
		logger.info("调用智能机器人接口请求参数：{}。", reqParams);
		String result = (String) executeGet(baseUri, reqParams);
		long t2 = System.currentTimeMillis();
		logger.info("调用智能机器人返回结果，{}，耗时：{}毫秒。", result, (t2 - t1));
		boolean isActiveSimulate = getContext().getServiceUtil().getConfiguration()
				.getBoolean("OMIIS_IS_ACTIVE_SIMULATE");
		if (isActiveSimulate) {
			return (T) simulateAnswer();
		}
		return (T) result;
	}
}
